package com.example.myapplication.tools;

import android.app.ProgressDialog;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.myapplication.config.AppConfigurate;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.File;
import java.io.FileOutputStream;

public class WebAsyncHttpUtils {

	public static final int ASYNC_ERROR = 300;
	public static final int ASYNC_SUCCESS = 301;
	
	ToastUtils tUtils = new ToastUtils();
	/**
	 * get 请求网络
	 * @param client
	 * @param method    /version/check
	 * @param params
	 * @param handler
	 */
	public static void getAsync(AsyncHttpClient client,final String method,RequestParams params,final Handler handler,final int flag){
    	//GET
    	//http://192.168.0.104/api/version/check?version=0&client=android
//		params.put("serverDeviceId", AppConfigurate.DEVICE_CODE);
//		if(AppConfigurate.client != null){
//			params.put("serverUserId", AppConfigurate.client.getId());
//		}
    	client.get(AppConfigurate.START_IP + method,params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
								  Throwable error) {
				if(handler!=null){
					Message msg = new Message();
					msg.what = ASYNC_ERROR;
					msg.arg1 = flag;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
				if(handler!=null){
					Message msg = new Message();
					msg.what = ASYNC_SUCCESS;
					msg.obj = new String(responseBody);
					msg.arg1 = flag;
					handler.sendMessage(msg);
				}
				System.out.println("getAsync: " +method + " - "+new String(responseBody));
			}
    	});
    }

	/**
	 * post 请求网络
	 * @param client
	 * @param method   如 /account/login
	 * @param params
	 * @param handler
	 */
	public static void postAsync(AsyncHttpClient client,final String method,RequestParams params,final Handler handler,final int flag){
//		params.put("serverDeviceId", AppConfigurate.DEVICE_CODE);
//		if(AppConfigurate.client != null){
//			params.put("serverUserId", AppConfigurate.client.getId());
//		}
    	client.post(AppConfigurate.START_IP + method,params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] header, byte[] responseBody,
					Throwable error) {
				if(handler!=null){
					Message msg = new Message();
					msg.what = ASYNC_ERROR;
					msg.arg1 = flag;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onSuccess(int statusCode, Header[] header, byte[] responseBody) {
				if(handler!=null){
					Message msg = new Message();
					msg.what = ASYNC_SUCCESS;
					msg.obj = new String(responseBody);
					msg.arg1 = flag;
					handler.sendMessage(msg);
				}
				System.out.println("postAsync: " +method + " - "+new String(responseBody));
			}
    	});
    }

	/**
	 * post 文件上传
	 * @param client
	 * @param method	/api/fs/upload
	 * @param params	params.put("fileName", new File(downFilePath));
	 * @param handler
	 */
	static int postTemp = 0;
	public static void filePostAsync(AsyncHttpClient client,final String method,RequestParams params
			,final Handler handler,final ProgressDialog pd,final int flag){
		pd.setTitle("系统提示");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setIndeterminate(false);
        pd.setCanceledOnTouchOutside(false);
        pd.setMax(100);
        pd.show();
        postTemp = 0;
    	client.post(AppConfigurate.START_IP + method,params, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] header, byte[] responseBody,
					Throwable error) {
				pd.cancel();
				if(handler != null){
					Message msg = new Message();
					msg.what = ASYNC_ERROR;
					msg.arg1 = flag;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onSuccess(int statusCode, Header[] header, byte[] responseBody) {
				pd.cancel();
				if(handler != null){
					Message msg = new Message();
					msg.what = ASYNC_SUCCESS;
					msg.obj = new String(responseBody);
					msg.arg1 = flag;
					handler.sendMessage(msg);
				}
				System.out.println("filePostAsync: " +method + " - "+ new String(responseBody));
			}

			@Override
			public void onProgress(long bytesWritten, long totalSize) {
				super.onProgress(bytesWritten, totalSize);
				int test = FileUtils.formatInteger((double)bytesWritten / (double)totalSize);
				if(test > postTemp){
					postTemp = test;
					pd.setProgress(postTemp);
					pd.notify();
				}
			}
    	});
    }

    /**
     * 下载文件
     * @param client
     * @param httpPath	HTTP全路径
     * @param handler
     * @param pd		进度条
     * @param flag
     */
	static int getTemp = 0;
	public static void fileGetAsync(AsyncHttpClient client,String httpPath,final String downFilePath,final Handler handler
			,final ProgressDialog pd,final int flag){
    	File parentFile = new File(Environment.getExternalStorageDirectory() + "/down/");
        if(!parentFile.exists()){
        	parentFile.mkdirs();
        }
	    System.out.println(parentFile.getPath());
//	    String[] allowedContentTypes = new String[] { "image/png", "image/jpeg",
//	    		"application/vnd.android.package-archive","video/mpeg4","text/xml" ,"application/msword" , "text/plain"};\
	    //下载APK后缀
//	    String[] allowedContentTypes = new String[] { "application/vnd.android.package-archive"};
//	    pd = new ProgressDialog(pd1.getContext());
		pd.setTitle("系统提示");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setIndeterminate(false);
        pd.setCanceledOnTouchOutside(false);
        pd.setMax(100);
        pd.show();
        getTemp = 0;
    	client.get(httpPath
    			, new BinaryHttpResponseHandler() {
	    //http://www.pc6.com/down.asp?id=52383
	    //http://192.168.0.106/files/sy_0_1_1.apk
    	//http://c.hiphotos.baidu.com/zhidao/pic/item/d31b0ef41bd5ad6e9fcac3c683cb39dbb6fd3cee.jpg
    	//http://d04.res.meilishuo.net/pic/_o/6d/9e/592598ef080085002e39959f9555_541_626.c6.jpeg_d01cb979_s1_q0_150_5_0_226_800.jpg
    	//http://106.119.188.16/mp3.9ku.com/9kuplayer.exe

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				pd.cancel();
				Message msg = new Message();
				msg.what = ASYNC_ERROR;
				msg.arg1 = flag;
				handler.sendMessage(msg);
			}

			@Override
			public void onProgress(long bytesWritten, long totalSize) {
				super.onProgress(bytesWritten, totalSize);
				int test = FileUtils.formatInteger((double)bytesWritten / (double)totalSize);
				if(test > getTemp){
					getTemp = test;
					pd.setProgress(getTemp);
					pd.notify();
				}
//				System.out.println(test + "  总大小:" + FileUtils.formatFileSize(totalSize) +
//						",当前下载量：" + FileUtils.formatFileSize(bytesWritten) + ",下载进度：" + FileUtils.formatDouble((double)bytesWritten / (double)totalSize) + "%");
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
//				String downFilePath = Environment.getExternalStorageDirectory() + "/down/ucsaa.jpg";
    	        File file2 = new File(downFilePath);
    	        try {
    	            FileOutputStream oStream = new FileOutputStream(file2);
    	            oStream.write(arg2);
    	            oStream.flush();
    	            oStream.close();
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	            Log.i(null, e.toString());
    	        }
    	        pd.cancel();
    	        Message msg = new Message();
				msg.what = ASYNC_SUCCESS;
				msg.arg1 = flag;
				handler.sendMessage(msg);
			}
    	});
    }
}
